from flask import Blueprint, request, jsonify, send_file
from models import db, Contract, Employee
from datetime import datetime, date
import openpyxl
from openpyxl.utils import get_column_letter
from io import BytesIO
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side

contract_bp = Blueprint('contract', __name__)

# @contract_bp.route('/api/contracts', methods=['GET'])
# def get_contracts():
#     contracts = Contract.query.all()
#     return jsonify([contract.to_dict() for contract in contracts])

# @contract_bp.route('/api/contracts', methods=['POST'])
# def create_contract():
#     data = request.get_json()
#     contract = Contract(**data)
#     db.session.add(contract)
#     db.session.commit()
#     return jsonify({'message': '创建成功', 'id': contract.id}), 201

# @contract_bp.route('/api/contracts/<int:id>', methods=['PUT'])
# def update_contract(id):
#     contract = Contract.query.get_or_404(id)
#     data = request.get_json()
#     for key, value in data.items():
#         if key in ('start_date', 'end_date') and isinstance(value, str):
#             setattr(contract, key, datetime.fromisoformat(value.split('T')[0]).date())
#         else:
#             setattr(contract, key, value)
#     db.session.commit()
#     return jsonify({'message': '修改成功'})

# @contract_bp.route('/api/contracts/<int:id>', methods=['DELETE'])
# def delete_contract(id):
#     contract = Contract.query.get_or_404(id)
#     db.session.delete(contract)
#     db.session.commit()
#     return jsonify({'message': '删除成功'})

@contract_bp.route('/api/contracts/export/excel', methods=['GET'])
def export_contracts_excel():
    try:
        # 查询所有合同
        contracts = Contract.query.all()

        # 定义要导出的字段 (排除ID、创建时间和更新时间)
        fields = [
            ('contract_number', '合同编号'),
            ('contract_type', '合同类型'),
            ('contract_party', '合同主体'),
            ('employee_name', '关联员工'), # 需要从Employee模型获取
            ('start_date', '签订日期'),
            ('end_date', '到期日期'),
            ('is_expired', '是否到期'),
        ]

        # 创建Excel工作簿和工作表
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = '合同列表'

        # 样式定义 (根据通用规则)
        header_font = Font(bold=True, color='FFFFFF')
        header_fill = PatternFill('solid', fgColor='4F81BD')
        center_alignment = Alignment(horizontal='center', vertical='center')
        thin_border = Border(
            left=Side(style='thin'),
            right=Side(style='thin'),
            top=Side(style='thin'),
            bottom=Side(style='thin')
        )

        # 写入表头并应用样式
        for col, (_, header) in enumerate(fields, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = center_alignment
            cell.border = thin_border

        # 写入数据并应用样式
        for row, contract in enumerate(contracts, 2):
            employee_name = Employee.query.get(contract.employee_id).name if contract.employee_id else ''
            data_row = [
                contract.contract_number,
                contract.contract_type,
                contract.contract_party,
                employee_name,
                contract.start_date,
                contract.end_date,
                '是' if contract.is_expired else '否',
            ]
            for col, value in enumerate(data_row, 1):
                # 格式化日期时间字段
                if isinstance(value, (datetime, date)):
                     value = value.strftime('%Y-%m-%d') # 合同日期通常只显示日期

                cell = ws.cell(row=row, column=col, value=value)
                cell.alignment = center_alignment
                cell.border = thin_border

        # 自动调整列宽 (根据通用规则，并考虑中文字符)
        for col in ws.columns:
            max_length = 0
            column = col[0].column_letter
            for cell in col:
                try:
                    if cell.value:
                        # 估算中文字符宽度
                        length = len(str(cell.value).encode('gbk'))
                        max_length = max(max_length, length)
                except:
                    pass
            # 设置列宽，增加一些额外空间
            adjusted_width = (max_length + 4) if max_length > 0 else 10
            ws.column_dimensions[column].width = adjusted_width

        # 保存到内存并发送文件
        output = BytesIO()
        wb.save(output)
        output.seek(0)

        return send_file(
            output,
            as_attachment=True,
            download_name='合同列表.xlsx',
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

    except Exception as e:
        # 简单的错误处理
        return jsonify({'error': str(e)}), 500 